import Config from './config.js'
//import JSEncrypt from 'jsencrypt'

import Util from './util.js'

// #ifdef H5

const app_type = 'h5';
const app_type_name =  'H5';
// #endif

// #ifdef MP-WEIXIN
const app_type = 'weapp';
const app_type_name = '微信小程序';
// #endif

// #ifdef APP-PLUS
const app_type = 'app';
const app_type_name = 'APP';
// #endif

export default {
	sendRequest(params) {
		var _this=this
		var method = params.data != undefined ? 'POST' : 'GET', // 请求方式
			url = Config.baseUrl + params.url, // 请求路径
			data = {
				app_type,
				app_type_name
			};

		// token
		if (uni.getStorageSync('token')) data.token = uni.getStorageSync('token');
		// 参数
		if (params.data != undefined) Object.assign(data, params.data);

		if (params.async === false) {
			//同步
			return new Promise((resolve, reject) => {
				uni.request({
					url: url,
					method: method,
					data: data,
					header: params.header || {
						'content-type': 'application/x-www-form-urlencoded;application/json'
					},
					dataType: params.dataType || 'json',
					responseType: params.responseType || 'text',
					success: (res) => {
						
						if (res.data.data.code == -10009 || res.data.data.code == -10010) {
							uni.showToast({
								title:"异地登陆提醒",
								duration:5000,
								icon:"error",
								mask:true
							})
							setTimeout(function(){
								uni.removeStorageSync("token")
								uni.navigateTo({
									url:"/pages/public/login"
								})
							},3000)
						}
						resolve(res.data);
					},
					fail: (res) => {
						reject(res);
					},
					complete: (res) => {
						reject(res);
					}
				});
			});
		} else {
			//异步
			uni.request({
				url: url,
				method: method,
				data: data,
				header: params.header || {
					'content-type': 'application/x-www-form-urlencoded;application/json'
				},
				dataType: params.dataType || 'json',
				responseType: params.responseType || 'text',
				success: (res) => {
					// if (res.data.data.refreshtoken) {
					// 	uni.setStorage({
					// 		key: 'token',
					// 		data: res.data.refreshtoken
					// 	});
					// }
					if (res.data.data.code == -10009 || res.data.data.code == -10010) {
						uni.showToast({
							title:"异地登陆提醒",
							duration:3000,
							icon:"error",
							mask:true
						})
						setTimeout(function(){
							uni.removeStorageSync("token")
							uni.navigateTo({
								url:"/pages/public/login"
							})
						},3000)
					}
					typeof params.success == 'function' && params.success(res.data);
				},
				fail: (res) => {
					typeof params.fail == 'function' && params.fail(res);
				},
				complete: (res) => {
					typeof params.complete == 'function' && params.complete(res);
				}
			});
		}
	}
}
